import { Context } from "koa";
import { Model } from "sequelize-typescript";

/*
 * @Author: DUST
 * @Date: 2023-05-28 09:50:07
 * @LastEditors: DUST
 * @LastEditTime: 2023-06-06 14:58:59
 * @FilePath: \koa-node-ts\utils\pagination.ts
 * @Description:
 * undefined
 */
class pagination<T extends Model> {
  /**
   * @description: 分数数据统一格式
   * @param {Array} data：分页源数据
   * @param {number} pageSize：每页最大条数
   * @param {number} total：数据总数
   * @param {number} pageNumber：当前页码
   */
  public doPaginate(
    data: Array<T>,
    pageSize: number = 10,
    total: number = 0,
    pageNumber: number = 0
  ) {
    return {
      list: data,
      pageNumber,
      pageSize,
      pages: Math.ceil(total / pageSize),
      total,
      currentPage: pageNumber,
    };
  }
  /**
   * @description: 获取分页接口分页参数
   * @param {Context} ctx:请求体
   */  
  public getPageParams(ctx: Context): {
    pageNumber: number;
    pageSize: number;
  } {
    const params = new URLSearchParams(ctx.querystring);
    let pageSize = 10;
    let pageNumber = 1;
    if(params.get("pageNumber") !== null && !isNaN(Number(params.get("pageNumber")))) {
      pageNumber = Number(params.get("pageNumber"));
    }
    if(params.get("pageSize") !== null && !isNaN(Number(params.get("pageSize")))) {
      pageSize = Number(params.get("pageSize"));
    }

    return {
      pageNumber,
      pageSize
    }
  }
}

export default new pagination;
